import items from "./routes.ts";

//基础头部设置(主要用作排序)
const headers = [
    {
        title: undefined,
        hidden: false,
    },
    {
        title: "SYSTEM",
        hidden: false,
    },
    {
        title: "EXAMPLE",
        hidden: false,
    },
]

//获取导航集合
const getNavs = function(node: any, path: string) :any[]{
    let res = [];
    for (let i = 0; i < node.length; i++) {
        let item = node[i];
        //获取子项路径
        let itemPath = ""
        if(item?.path?.length > 0 && item?.path[0] == "/"){
            itemPath = item?.path;
        }
        else if(item?.path?.length == 0){
            itemPath = path;
        }
        else {
            itemPath = path + "/" + item?.path;
        }
        //判断是否隐藏
        if(item?.meta?.hidden)
            continue;
        //执行子项提取
        if(item?.meta?.title){
            if(item?.children){
                res.push({
                    path: undefined,
                    ...item?.meta,
                    childList: getNavs(item?.children, itemPath)
                })
            } else {
                res.push({
                    path: itemPath || "/",
                    ...item?.meta,
                })
            }
        } else {
            if(item?.children){
                res.push(...getNavs(item?.children, itemPath))
            }
        }
    }
    return res;
};

//执行添加排序处理
const handlerSort = function(a: any, b: any) :(number | boolean) {
    return (a?.sort || 99) - (b?.sort || 99)
};

//执行添加头处理
const handlerHeader = function(navs: any[]) {
    //处理成集合
    let set: { [key:string]: any } = {};
    for (let i = 0; i < headers.length; i++) {
        set[headers[i]?.title ?? "undefined"] = {
            title: headers[i]?.title,
            hidden: headers[i]?.hidden,
            children: [],
        };
    }
    for (let i = 0; i < navs.length; i++) {
        if(navs[i]?.header && set[navs[i].header] === undefined){
            set[navs[i].header] = {
                title: navs[i].header,
                hidden: false,
                children: [],
            }
        }
        set[navs[i].header]?.children.push(navs[i]);
    }

    //处理处理结果
    let res = [];
    for (let name in set) {
        if(name != "undefined" && set[name].hidden != true){
            res.push({
                type: "header",
                title: name,
            })
        }
        res.push(...set[name].children.sort(handlerSort));
    }

    //返回处理结果
    return res;
};

//定义导航列表
const navs = handlerHeader(getNavs(items, ""));

//返回导航列表
export default navs;